# -*- coding: utf-8 -*-
"""management of works"""
import threading
import os
import time

class MonkeyServices(object):
    """class of LDAP management"""
    #执行monkey测试脚本
    def monkey_adb(self,seed,apptype):
        cmd = 'adb shell monkey -p '+apptype+' -s ' + seed + ' --throttle 100 --ignore-crashes --ignore-timeouts --monitor-native-crashes --pct-touch 20 --pct-motion 20 --pct-pinchzoom 10 --pct-majornav 15 --pct-syskeys 3 --pct-appswitch 20 --pct-flip 10 --pct-anyevent 2 --ignore-crashes --ignore-timeouts --monitor-native-crashes -v-v-v 2000 > monkeyLog.txt'
        print cmd
        os.popen(cmd)
        # 读取文件最后一行，判断monkey是否执行结束
        fname = 'monkeyLog.txt'
        res=1
        with open(fname, 'r') as f:  # 打开文件
            first_line = f.readline()  # 读第一行
            off = -50  # 设置偏移量
            while True:
                f.seek(off, 2)  # seek(off, 2)表示文件指针：从文件末尾(2)开始向前50个字符(-50)
                lines = f.readlines()  # 读取文件指针范围内所有行
                if len(lines) >= 2:  # 判断是否最后至少有两行，这样保证了最后一行是完整的
                    last_line = lines[-1]  # 取最后一行
                    break
                # 如果off为50时得到的readlines只有一行内容，那么不能保证最后一行是完整的
                # 所以off翻倍重新运行，直到readlines不止一行
                off *= 2
            print '文件' + fname + '最后一行为：' + last_line
            if last_line == '// Monkey finished':
                res=0

    #读取monkeylog获取相应信息
    def readMonkeyLog(self):
        countAnr=0;
        countCrash=0;
        countException=0;
        file = open("monkeyLog.txt")
        while 1:
            line = file.readline()
            if not line:
                break
            if 'seed' in line:
                seedVal=line.split(' ')[1]
                seedNum=seedVal[seedVal.index('=')+1:]
            if 'AllowPackage' in line:
                packageName=line.split(' ')[1]
            if 'ANR' in line.upper():
                countAnr+=1
            if 'CRASH' in line.upper():
                countCrash+=1
            if 'EXCEPTION' in line.upper():
                countException+=1
        if countAnr==0 and countCrash==0 and countException==0:
            result="通过"
        else:
            result="不通过"
        valueList={
            'seed':seedNum,
            'packageName':packageName,
            'anr':countAnr,
            'crash':countCrash,
            'exception':countException,
            'result':result
        }
        return valueList

